package com.yequan.socket.basae;

import java.io.*;
import java.net.Socket;

/**
 * @author : Administrator
 * @date : 2020/2/14
 */
public class Client {

    public static void main(String[] args) throws IOException, InterruptedException {
        final int length = 100;
        String host = "127.0.0.1";
        int port = 1122;
        Socket[] sockets = new Socket[length];
        for (int i = 0; i < length; i++) {
            sockets[i] = new Socket(host, port);
            System.out.println("第 " + (i + 1) + " 次连接成功!");
            sendMessage(sockets[i], i);
            acceptMessage(sockets[i], i);
        }
        Thread.sleep(3000);
        for (int i = 0; i < length; i++) {
            sockets[i].close();
        }
    }

    private static void acceptMessage(Socket socket, int i) throws IOException {
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        StringBuffer stringBuffer = new StringBuffer();
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        System.out.println("我是[" + (i + 1) + "]号特工,总部的命令是: " + stringBuffer.toString());
        bufferedReader.close();
        inputStream.close();
        socket.shutdownInput();
    }

    private static void sendMessage(Socket socket, int i) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        PrintWriter printWriter = new PrintWriter(outputStream);
        printWriter.write("你好总部,我是[" + (i + 1) + "]号特工");
        printWriter.flush();
        socket.shutdownOutput();
        printWriter.close();
        outputStream.close();
    }


}
